package com.singfan.core.util;

import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.PingppException;
import com.pingplusplus.model.Charge;
import com.singfan.common.ServerEnv;
import com.singfan.core.dao.database.model.constant.PayChannelType;

import java.util.HashMap;
import java.util.Map;

/**
 * Author: hansonghe
 * Date: 2015-08-27 10:26
 * Desc:
 */
public class PayUtil {
    private static final String API_KEY_TEST = "sk_test_1i9CeHGivPu5z90u9Se9eTSG";
    private static final String API_KEY_LIVE = "sk_live_nMnwcL8fzWdhdiVltgi29YmY";

    private static final String APP_ID = "app_5arn50CePG844W58";

    /**
     * Ping++支付
     * @param amount 支付金额
     * @param subject 支付标题
     * @param body 支付内容
     * @param orderId 订单id
     * @param payChannel 支付渠道
     * @param clientIp 支付客户端的ip
     * @return 支付结果(不为null即为成功)
     */
    public static Charge charge(int amount, String subject, String body, String orderId, int payChannel, String clientIp){
        Pingpp.apiKey = getApiKey();
        Charge charge = null;
        try {
            Map<String, Object> chargeMap = new HashMap<>();
            Map<String, String> app = new HashMap<>();
            app.put("id",APP_ID);
            chargeMap.put("app", app);
            chargeMap.put("amount", amount);
            chargeMap.put("currency", "cny");
            chargeMap.put("subject", subject);
            chargeMap.put("body", body);
            chargeMap.put("order_no", orderId);
            chargeMap.put("channel", getPayChannelText(payChannel));
            chargeMap.put("client_ip", clientIp);

            //发起交易请求
            charge = Charge.create(chargeMap);
        }
        catch (PingppException e) {
            e.printStackTrace();
        }
        return charge;
    }

    private static String getPayChannelText(int payChannelValue){
        String result;
        if (payChannelValue == PayChannelType.PAY_ALI){
            result = "alipay";
        }
        else if (payChannelValue == PayChannelType.PAY_WX){
            result = "wx";
        }
        else if (payChannelValue == PayChannelType.PAY_UNION){
            result = "upacp";
        }
        else {
            result = null;
        }

        return result;
    }

    private static String getApiKey(){
        if (ServerEnv.isRelease()){
            return API_KEY_LIVE;
        }
        return API_KEY_TEST;
    }
}
